<script lang="ts" setup>
import type { TenantForm } from '@/api/tenant/types'
import * as tenant from '@/api/tenant'
import type { FormRules } from 'element-plus'

const dialogVisible = ref(false)
const dialogProp = reactive<ModalWindowProp>({
    title: ''
})

const formRef = ref()
const formData = ref<TenantForm>({
    name: ''
})
const rules = reactive<FormRules<TenantForm>>({
    name: [
        { required: true, message: '请输入租户名称' },
        { max: 32, message: '租户名称长度不能超过32个字符' }
    ]
})

const open = async (prop: ModalWindowProp) => {
    if(prop.context !== undefined) {
        dialogProp.context = prop.context
        formData.value = await tenant.form(dialogProp.context)
    }

    dialogProp.title = prop.title
    dialogVisible.value = true
}
defineExpose({
    open
})

const emit = defineEmits(['close'])

const save = async () => {
    if(!formRef.value.validate()) {
        return
    }

    if(dialogProp.context === undefined) {
        await tenant.add(formData.value)
    } else {
        await tenant.edit(dialogProp.context, formData.value)
    }

    dialogVisible.value = false
    emit('close')
}
</script>

<template>
    <el-dialog v-model="dialogVisible" :title="dialogProp.title" width="35%" :destroy-on-close="true">
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="租户名称" prop="name">
                <el-input v-model="formData.name"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="save">保存</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>